package com.salton123.colorflydemo.ui.aty

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder
import cn.bingoogolapple.refreshlayout.BGARefreshLayout
import com.salton123.C
import com.salton123.bmob.biz.mandala.MandalaCore
import com.salton123.colorflydemo.R
import com.salton123.colorflydemo.ui.adapter.MandalaMainAdapter
import com.salton123.feature.ImmersionFeature
import com.salton123.ui.base.BaseActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.aty_mandala_main.*

/**
 * User: newSalton@outlook.com
 * Date: 2019/6/3 14:24
 * ModifyTime: 14:24
 * Description:
 */
class MandalaMainAty : BaseActivity(), BGARefreshLayout.BGARefreshLayoutDelegate {
    private var page: Int = 1
    private val mAdapter: MandalaMainAdapter by lazy { MandalaMainAdapter(recyclerView) }
    override fun initViewAndData() {
        mRefreshLayout.setDelegate(this)
        mRefreshLayout.setRefreshViewHolder(BGANormalRefreshViewHolder(activity(), true))
        mRefreshLayout.setIsShowLoadingMoreView(true)
        recyclerView.adapter = mAdapter
        recyclerView.layoutManager = GridLayoutManager(activity(), 2)
        getData(false)
        mAdapter.setOnRVItemClickListener { _, _, position ->
            var item = mAdapter.getItem(position)
            var bundle = Bundle()
            bundle.putParcelable(C.ARG_ITEM, item)
            openActivity(MandalaPaintBoardAty::class.java, bundle)
        }
//        FillTools.floodFill(null, 100,200,300,400)
    }

    @SuppressLint("CheckResult")
    fun getData(clear: Boolean) {
        MandalaCore.loadItem(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ p0 ->
                    if (p0?.size ?: 0 > 0) {
                        if (clear) {
                            mAdapter.clear()
                            mAdapter.addMoreData(p0)
                        } else {
                            mAdapter.addMoreData(p0)
                        }
                    } else {
                        longToast("数据加载完毕")
                    }
                }, { e -> e.printStackTrace() }
                )
    }

    override fun getLayout(): Int = R.layout.aty_mandala_main

    override fun initVariable(savedInstanceState: Bundle?) {
        addFeature(ImmersionFeature(this))
    }

    override fun onBGARefreshLayoutBeginLoadingMore(refreshLayout: BGARefreshLayout?): Boolean {
        page++
        getData(false)
        return false
    }

    override fun onBGARefreshLayoutBeginRefreshing(refreshLayout: BGARefreshLayout?) {
        page = 1
        getData(true)
        mRefreshLayout.endRefreshing()
    }
}
